﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace SimpleTerminal.Http
{
    class Api
    {
        public delegate void RequesetCallback(Response response);
        public static void DoRequest(string url, RequesetCallback requesetCallback)
        {
            Thread thread = new Thread((ThreadStart)delegate
            {
                string strResult = string.Empty;
                try
                {
                    HttpWebRequest hwRequest = (HttpWebRequest)WebRequest.Create(url);
                    //hwRequest.Timeout = 30000;
                    hwRequest.Method = "GET";
                    hwRequest.ContentType = "application/x-www-form-urlencoded";

                    HttpWebResponse hwResponse = (HttpWebResponse)hwRequest.GetResponse();
                    StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.ASCII);
                    strResult = srReader.ReadToEnd();
                    srReader.Close();
                    hwResponse.Close();
                }
                catch (Exception)
                {
                }
                Response response = ToJson(strResult);
                try
                {
                    requesetCallback(response);

                }
                catch (Exception)
                {

                }
            });
            thread.IsBackground = true;
            thread.Start();
        }

        private static Response ToJson(string jsonText)
        {
            Response response = JsonConvert.DeserializeObject<Response>(jsonText);
            return response;
        }
    }
}
